<template>
	<div style="background: #eee;padding: 10px;">
		<div style="margin-bottom: 10px">
			<Input v-model="itemname" placeholder="输入商品名称" style="width: 300px" clearable/>
			<Input v-model="itemprice" placeholder="输入商品单价" style="width: 300px" clearable/>
			<Button type="primary" @click="subitem()">添加商品</Button>
		</div>
		<Table ref="table" height="600" :loading="loading" stripe border :columns="cols" :data="data"/>
		<Page ref="page" :total="count" :page-size="size" show-total show-elevator show-sizer @on-change="change" @on-page-size-change="pageChange" style="float: right;margin-top: 15px;margin-bottom: 15px"/>
	</div>
</template>
<script>
	export default {
		data() {
			return {
				name: 'group_add',
				loading: true,
				cols: [
					{
						title: '商品名称',
						key: 'name',
						sortable: true,
						filters: [],
						filterMethod(value, row) {
							return row.name.indexOf(value) > -1;
						}
					},
					{
						title: '商品单价',
						sortable: true,
						key: 'price'
					},
					{
						title: '商品总量',
						sortable: true,
						key: 'total'
					}
				],
				data: [],
				count: 0,
				size: 15,
				tmpData: [],
				itemname: '',
				itemprice: ''
			}
		},
		methods: {
			getItemInfo() {
				this.$ajax({
					method: 'get',
					url: '/index/piece/getItemInfo',
				})
					.then(response => {
						this.tmpData = response.data.data;
						this.count = response.data.count;
						this.handleHistoryDate();
						this.doFilters();
						this.loading = false;
					})
					.catch(error => {
						console.log(error);
					});
			},
			handleHistoryDate() {
				if (this.count < this.size) {
					this.data = this.tmpData;
				} else {
					this.data = this.tmpData.slice(0, this.size);
				}
			},
			change(index) {
				let _start = (index - 1) * this.size;
				let _end = index * this.size;
				this.data = this.tmpData.slice(_start, _end);
			},
			pageChange(index) {
				this.size = index;
				this.handleHistoryDate();
			},
			doFilters() {
				const tmp = Array.from(new Set(this.data.map(function (k) {
					return k.name;
				})));
				this.cols[0].filters = tmp.map(function (k) {
					return {
						label: k,
						value: k
					}
				})
			},
			subitem() {
				this.$ajax({
					method: 'post',
					url: '/index/piece/doAddItem',
					data: {
						itemname: this.itemname,
						itemprice: this.itemprice
					}
				})
					.then(response => {
						if (response.data.code === 0) {
							this.itemname = "";
							this.itemprice = "";
							this.tmpData.push(response.data.data);
							this.count = this.count + 1;
							this.handleHistoryDate();
							this.$Notice.success({
								title: response.data.msg
							});
						} else {
							this.$Notice.error({
								title: response.data.msg
							});
						}
					})
					.catch(error => {
						console.log(error);
						this.$Notice.error({
							title: '操作失败'
						});
					});
			}
		},
		created() {
			this.getItemInfo();
		}
	}
</script>
